package com.xidian.yunwudemo.security.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
//@Component
public class TokenUtil {
//    private static final Logger LOGGER = LoggerFactory.getLogger(TokenUtil.class);
//    private static final int EXPIRATION_TIME = 12*3600*1000;
//    private static final String CLAIM_KEY_CREATED = "created";
//    private static final String SECRET_KEY = "027*9ee65814fc0cdb860474339a9cc9d039a75a45e3bdc63c3c5083a67c9646b";
//    public static final String TOKEN_PREFIX = "Bearer "; //此处有问题
//    public static final String AUTHORIZATION = "Authorization";
    private static final Logger LOGGER = LoggerFactory.getLogger(TokenUtil.class);
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    /**
     * 根据负载生成JWT的token
     */
    private String generateToken(Map<String,Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e){
            LOGGER.info("Jwt格式验证失败{}:",token);
        }
        return claims;
    }
    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() { return new Date(System.currentTimeMillis()+expiration*1000);}

    /**
     * 从token中提取用户名
     * @param token 客户端传入的token
     * @return userName 登录的用户名
     */
    public String getUserNameFromToken(String token){
        String userName;
        try {
            Claims claims = getClaimsFromToken(token);
            userName = claims.getSubject();
        } catch (Exception e){
            userName = null;
        }
        return userName;
    }
    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     * @param userDetails 从数据库中查询出来的用户信息
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token) ;
    }
    /**
     * 验证token是否过期
     * @param token 客户端传入的token
     * @return boolean
     */
    private boolean isTokenExpired(String token){
        Date expiredDate = getExpiredTimeFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     * @param token 客户端传入的token
     * @return date 过期的时间
     */
    private Date getExpiredTimeFromToken(String token){
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 根据用户信息生成token
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }
    /**
     * 当原来的token没过期时是可以刷新的
     *
     * @param oldToken 带tokenHead的token
     */
    public String refreshHeadToken(String oldToken){
        String token = oldToken.substring(tokenHead.length());
        if(StrUtil.isEmpty(token)) {
            return null;
        }
        // token校验不过
        Claims claims = getClaimsFromToken(token);
        if(claims == null) {
            return null;
        }
        // token过期，不支持刷新
        if(isTokenExpired(token)){
            return null;
        }
        // 如果之前刷新过，则返回原token(可以理解为指定时间内不执行刷新操作)
        if(tokenRefreshBefore(token,30*60)){
            return token;
        }else {
            claims.put(CLAIM_KEY_CREATED,new Date());
            return generateToken(claims);
        }
    }
    /**
     * 判断token在指定时间内是否刚刚刷新过
     * @param token 原token
     * @param times 指定时间（秒）
     */
    private boolean tokenRefreshBefore(String token, int times){
        Claims claims = getClaimsFromToken(token);
        Date created = claims.get(CLAIM_KEY_CREATED,Date.class);
        Date refreshDate = new Date();
        // 此处我不理解
        // 刷新时间在创建时间的指定时间内
        if(refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created,times))){
            return true;
        }
        return false;
    }
}
